﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HCFramework.API.LINQ;
using Telerik.Web.UI;

namespace HCFramework.Product.PropertyManage
{
    public partial class ChooseProperty : System.Web.UI.UserControl
    {
        public RadTreeView Tree
        {
            get
            {
                return RadComboBox1.Items[0].FindControl("RadTreeView1") as RadTreeView;
            }
        }

        public int? SelectedPropertyID
        {
            get
            {
                if (Tree.SelectedNode == null || !IsPropertyNode(Tree.SelectedNode)) return null;
                return int.Parse(Tree.SelectedValue);
            }
            set
            {
                Tree.ClearSelectedNodes();
                if (value.HasValue)
                {
                    RadTreeNode node = Tree.GetAllNodes().Where(ik => IsPropertyNode(ik) && ik.Value == value.Value.ToString()).First();
                    node.Selected = true;
                    node.ExpandParentNodes();
                    SetText(node.Text);
                }
            }
        }

        private bool IsPropertyNode(RadTreeNode radTreeNode)
        {
            string text = radTreeNode.Text;
            return text.StartsWith("(") && text.EndsWith(")");
        }

        public void SetText(string text)
        {
            RadComboBox1.Items[0].Text = text;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //LoadTreeData();
            }
            SelectedPropertyID = SelectedPropertyID;
        }

        public void LoadTreeData()
        {
            // Load category
            HCDataContext db = new HCDataContext();
            Tree.DataSource = db.ProductCategories.OrderBy(ik => ik.OrderDisplay);
            Tree.DataBind();

            // Load property
            foreach (RadTreeNode leafNode in Tree.GetAllNodes().Where(ik => ik.Nodes.Count < 1))
            {
                int catID = int.Parse(leafNode.Value);
                ProductCategory cat = C.ProductCategoryController.GetByID(catID);
                foreach (ProductProperty property in cat.ProductProperties)
                {
                    RadTreeNode propertyNode = new RadTreeNode("(" + property.Name + ")", property.ProductPropertyID.ToString());
                    propertyNode.Font.Bold = true;
                    leafNode.Nodes.Add(propertyNode);
                }
            }
        }

        protected void RadTreeView1_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            //RadComboBox1.Items[0].Text = e.Node.Text;
        }
    }
}